//###############
//FILE : FileWantFileSession.java
//WRITER : Daniel Lowengrub, daniel_i_l, 320687098
//EXERCISE : oop ex3 2011
//DESCRIPTION:
//See below
//###############

package oop.ex3.protocol.sessions;

import oop.ex3.protocol.messages.FileNotFoundMsg;
import oop.ex3.protocol.messages.WantFileMsg;
import oop.ex3.protocol.messages.FileAddressMsg;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.util.ArrayList;

import oop.ex3.communication.SocketAddress;
import oop.ex3.exceptions.InvalidMessageException;

/**
 * Ask a NS for a list of all the FM that contain a certain file.
 * @author daniel
 */
public class FileWantFileSession extends FileToNameSession {
    private String _fileName;
    private ArrayList<SocketAddress> _fileServers;

    /**
	 * Create a new session.
	 */
    public FileWantFileSession() {
        super();
        _fileServers = new ArrayList<SocketAddress>();

    }

    /**
     * Set the file name we want to ask for.
     * @param fileName The file name.
     */
    public void setFileName(String fileName) {
        _fileName = fileName;
    }

    /**
     * Get a list of addresses of all the FM's that contain the file we asked for.
     * @return
     */
    public ArrayList<SocketAddress> getFileServers() {
        return _fileServers;
    }


    @Override
    protected boolean specExecuteSession(DataInputStream inputStream, DataOutputStream outputStream) throws IOException, InvalidMessageException {
        if(!initSession(inputStream, outputStream))
            return false;

        WantFileMsg wantFile = new WantFileMsg();
        wantFile.setFileName(_fileName);
        wantFile.send(outputStream);

        FileNotFoundMsg fileNotFound = new FileNotFoundMsg();
        if (fileNotFound.matchHeader(inputStream)) {
        	fileNotFound.receive(inputStream);
        	//System.out.println("File not found , ending session");
        	endSession(inputStream, outputStream);
        	return false;
        }
        //receive the list of files
        while (!_endList.matchHeader(inputStream)) {
            FileAddressMsg fileAddress = new FileAddressMsg();
            fileAddress.receive(inputStream);
            String  ip = fileAddress.getIp();
            int port = fileAddress.getPort();
            _fileServers.add(new SocketAddress(ip, port));
        }

        _endList.receive(inputStream);
        
        if(!endSession(inputStream, outputStream))
            return false;

        return true;
    }

}
